package com.example.alphabetindexer.widget;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.alphabetindexer.R;

/**
 * 字母导航列表的基类Activity
 * @author atearsan/2013年8月4日
 *
 */
public abstract class AlphabetIndexerActivity extends Activity implements TextWatcher {
	/** 分组的布局 */
	//private LinearLayout titleLayout;

	/** 弹出式分组的布局 */
	private RelativeLayout sectionToastLayout;

	/** 右侧可滑动字母表 */
	private ImageView ivAlphabet;

	/** 分组上显示的字母 */
	//private TextView title;

	/** 弹出式分组上的文字 */
	private TextView sectionToastText;

	/** 存放内容List的ListView */
	protected ListView itemListView;

	/** 上次第一个可见元素，用于滚动时记录标识 */
	private int lastFirstVisibleItem = -1;

	/** 搜索输入框 */
	private EditText searchText;

	/** 搜索输入框的输入值 */
	private String searchString;
	private SearchListTask curSearchTask = null;
	private Object searchLock = new Object();

	/** 过滤数据. 搜索用到 */
	private List<AlphabetIndexerBean> beanFilterList = new ArrayList<AlphabetIndexerBean>();

	/** 数据List */
	private List<AlphabetIndexerBean> beanList = new ArrayList<AlphabetIndexerBean>();

	/** 字母导航适配器基类 */
	protected AlphabetIndexerAdapter adapter;

	/** 用于进行字母表分组 */
	private AlphabetSectionIndexer indexer;
	
	/** 是否是搜索模式 */
	protected boolean inSearchMode = false;
	
	/**
	 * 子类必须在 {@link #onCreate(Bundle)} 中setContentView后调用……
	 */
	protected void initView() {
		//titleLayout = (LinearLayout) findViewById(R.id.alphabetTitleLayout);
		itemListView = (ListView) findViewById(R.id.alphabetListView);
		itemListView.setFastScrollEnabled(true);
		
		sectionToastText = (TextView) findViewById(R.id.alphabetSectionToastText);
		//title = (TextView) findViewById(R.id.alphabetTitle);
		sectionToastLayout = (RelativeLayout) findViewById(R.id.alphabetSectionToastLayout);
		ivAlphabet = (ImageView) findViewById(R.id.alphabetImageView);

		searchText = (EditText) findViewById(R.id.alphabetSearchText);
		searchText.addTextChangedListener(this);
	}
	
	/**
	 * list数据加载完成之后调用<br>
	 * <i>List要先排序</i>
	 */
	protected void onBeanListPrepared(AlphabetIndexerAdapter adapter) {
		// 如果是未排序的List, 要先排序.
		// Collections.sort(beanFilterList, new AlphabetIndexerComparator());

		this.adapter = adapter;
		itemListView.setAdapter(this.adapter);
		
		// indexer
		indexer = new AlphabetSectionIndexer(beanList);
		this.adapter.setIndexer(indexer);
		setContentListView();
		setAlpabetListener();
	}
	
	protected void add(AlphabetIndexerBean bean) {
		beanList.add(bean);
	}

	protected List<AlphabetIndexerBean> getList() {
		return beanList;
	}
	
	protected List<AlphabetIndexerBean> getBeanFilterList() {
		return beanFilterList;
	}

	protected void clear() {
		if (beanList.size() > 0) {
			beanList.clear();
		}
	}

	/**
	 * 为联系人ListView设置监听事件，根据当前的滑动状态来改变分组的显示位置，从而实现挤压动画的效果。
	 */
	private void setContentListView() {
		itemListView.setAdapter(adapter);
		itemListView.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				//int section = indexer.getSectionForPosition(firstVisibleItem);
				//int nextSecPosition = indexer.getPositionForSection(section + 1);

				/*
				 * atearsan/2013-08-04 操! 会卡顿...先不要这个效果
				if (firstVisibleItem != lastFirstVisibleItem) {
					MarginLayoutParams params = (MarginLayoutParams) titleLayout.getLayoutParams();
					params.topMargin = 0;
					titleLayout.setLayoutParams(params);
					title.setText(indexer.getSectionTitle(section)); // atearsan/2013-08-02
				}
				*/

				/*
				 * atearsan/2013-08-04 因为有统一的head, title碰撞效果有问题
				// 如果相等, 说明下一个分组布局和顶部的分组布局相碰了
				if (nextSecPosition == firstVisibleItem + 1) {
					View childView = view.getChildAt(0); // 顶部分组布局
					if (childView != null) {
						int titleHeight = titleLayout.getHeight();
						int bottom = childView.getBottom(); // 底部距离父窗口的位置
						MarginLayoutParams params = (MarginLayoutParams) titleLayout
								.getLayoutParams();
						if (bottom < titleHeight) {
							float pushedDistance = bottom - titleHeight;
							params.topMargin = (int) pushedDistance;
							titleLayout.setLayoutParams(params);
						} else {
							if (params.topMargin != 0) {
								params.topMargin = 0;
								titleLayout.setLayoutParams(params);
							}
						}
					}
				}
				*/
				//lastFirstVisibleItem = firstVisibleItem;
			}
		});

	}

	/**
	 * 设置字母表上的触摸事件，根据当前触摸的位置结合字母表的高度，计算出当前触摸在哪个字母上。
	 * 当手指按在字母表上时，展示弹出式分组。手指离开字母表时，将弹出式分组隐藏。
	 */
	private void setAlpabetListener() {
		ivAlphabet.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				float alphabetHeight = ivAlphabet.getHeight();
				float y = event.getY();
				int sectionPosition = (int) ((y / alphabetHeight) / (1f / 27f));
				if (sectionPosition < 0) {
					sectionPosition = 0;
				} else if (sectionPosition > 26) {
					sectionPosition = 26;
				}
				
				String sectionLetter = (String) (indexer.getSections())[sectionPosition]; // atearsan/2013-08-02
				int position = indexer.getPositionForSection(sectionPosition);
				
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					ivAlphabet.setBackgroundResource(R.drawable.a_z_click);
					sectionToastLayout.setVisibility(View.VISIBLE);
					sectionToastText.setText(sectionLetter);
					itemListView.setSelection(position);
					break;
				case MotionEvent.ACTION_MOVE:
					sectionToastText.setText(sectionLetter);
					itemListView.setSelection(position);
					break;
				default:
					ivAlphabet.setBackgroundResource(R.drawable.a_z);
					sectionToastLayout.setVisibility(View.GONE);
				}
				return true;
			}
		});
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
	}

	/**
	 * 搜索
	 */
	@Override
	public void afterTextChanged(Editable s) {
		searchString = searchText.getText().toString().trim().toUpperCase();
		if (curSearchTask != null && curSearchTask.getStatus() != AsyncTask.Status.FINISHED) {
			try {
				curSearchTask.cancel(true);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		new SearchListTask().execute(searchString);
	}

	/**
	 * 搜索
	 * @author atearsan/2013年8月6日
	 *
	 */
	protected class SearchListTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... params) {
			beanFilterList.clear();

			String keyword = params[0];
			inSearchMode = (keyword.length() > 0);
			if (inSearchMode) {
				for (AlphabetIndexerBean bean : beanList) {
					if ((bean.getSortKey().indexOf(keyword.toUpperCase()) > -1)) {
						beanFilterList.add(bean);
					}
				}
			}
			return null;
		}

		protected void onPostExecute(String result) {
			synchronized (searchLock) {
				if (inSearchMode) {
					adapter.setBeanList(beanFilterList);
					adapter.notifyDataSetChanged();
				} else {
					adapter.setBeanList(beanList);
					adapter.notifyDataSetChanged();
				}
			}
		}

	} // End. SearchListTask
}